﻿//-----------------------------------------------------------------------
// <copyright file="BookDetailPage.xaml.cs" company="FIT VUT">
//     Copyright (c) FIT VUT. All rights are reserved.
// </copyright>
//----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

using BookCaching.Data;
using BookCaching.Data.Storage;
using BookCaching.Settings;
using BookCaching.Localization;

namespace BookCaching.Pages
{
    /// <summary>
    /// Page displays information about a specific book.
    /// </summary>
    public partial class BookDetailPage : PhoneApplicationPage
    {
        Knihotoc_WCFService.Knihotoc_WP7ServiceClient client;
        private Book book;
        //private User owner;
        ///private Place currentLocation;
        private string[] bookState = new string[] { "TestingState", "New", "Free", "Borrowed", "NeedMaintenance" };
        
        public BookDetailPage()
        {
            this.InitializeComponent();

            client = new Knihotoc_WCFService.Knihotoc_WP7ServiceClient();
            book = new Book();
            //owner = new User();
            //currentLocation = new Place();
        }

        private string convertNumberToBookState(int n)
        {
            try
            {
                return bookState[n];
            }
            catch
            {
                return LocalizedStrings.Get("BookStateNotFound");
            }
        }

        private void Client_GetPlaceByIdCompleted(object sender, Knihotoc_WCFService.GetPlaceByIdCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }
            
            Knihotoc_WCFService.Place place = e.Result;
            //TODO
            //currentLocationText.Text = place.Name + " " + place.Address.FullText +
            //        System.Environment.NewLine +
            //        "Lat: " + place.Address.Lat.ToString() + " Lon: " + place.Address.Lon.ToString();
        }

        private void Client_GetUserByIdCompleted(object sender, Knihotoc_WCFService.GetUserByIdCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }

            Knihotoc_WCFService.User owner = e.Result;

            addedByText.Text = owner.UserName;
        }

        private bool isCorrectBookPosition(float? lat, float? lon)
        {
            return (lat != null && lon != null);
        }

        private void Client_GetBookByIDCompleted(object sender, Knihotoc_WCFService.GetBookByIDCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                return;
            }

            Knihotoc_WCFService.Book b = e.Result;

            // convert Knihotoc_WCFService.Book to Book
            book.convertFromAzureServiceBook(b);

            book.ImageThumbnailVisibility = CurrentSettings.Instance.BookListThumbnailsVisibility;

            // fill data
            bookTitle.Text = book.Title;
            authorText.Text = book.Author.FullName;
            publishedYearText.Text = book.YearPublished.ToString();
            infoText.Text = convertNumberToBookState(book.BookState);

            if (book.ID == 3 || book.ID == 13 || book.ID == 29 || book.ID == 45 || book.ID == 61 || book.ID == 77 || book.ID == 93 || book.ID == 109)
            {
                StreamResourceInfo sr = Application.GetResourceStream(new Uri("Images/BookCovers/tri_kamaradi.jpg", UriKind.Relative));
                BitmapImage imageTriKamaradi = new BitmapImage();
                imageTriKamaradi.SetSource(sr.Stream);
                this.coverImage.Source = imageTriKamaradi;
            }
            else
            {
                try
                {
                    BitmapImage imageOnline = new BitmapImage(new Uri(book.CoverImagePath));
                    imageOnline.ImageFailed += new EventHandler<ExceptionRoutedEventArgs>(ImageOnline_ImageFailed);
                    coverImage.Source = imageOnline;
                }
                catch (UriFormatException)
                {
                    StreamResourceInfo sr = Application.GetResourceStream(new Uri("Images/NoImage.jpg", UriKind.Relative));
                    BitmapImage imageNoImage = new BitmapImage();
                    imageNoImage.SetSource(sr.Stream);
                    this.coverImage.Source = imageNoImage;
                }
            }

            // load owner from db
            client.GetUserByIdCompleted += Client_GetUserByIdCompleted;
            client.GetUserByIdAsync(book.OwnerRef);

            if (b.BookState == 2)
            {
                (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = true;
                (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = true;
                (ApplicationBar.Buttons[2] as ApplicationBarIconButton).IsEnabled = false;                
            }
            else
            {
                (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;
                (ApplicationBar.Buttons[1] as ApplicationBarIconButton).IsEnabled = false;
                (ApplicationBar.Buttons[2] as ApplicationBarIconButton).IsEnabled = true;
            }


            // try to load place from db
            client.GetPlaceByIdCompleted += Client_GetPlaceByIdCompleted;
            if (book.Address != null)
            {
                if (isCorrectBookPosition(book.Address.Lat, book.Address.Lon))
                {
                    currentLocationText.Text = "Lat: " + book.Address.Lat.ToString() + " Lon: " + book.Address.Lon.ToString();
                }
                else
                {
                    currentLocationText.Text = LocalizedStrings.Get("UnknowBookLocation");
                }
            }
            else
            {
                currentLocationText.Text = LocalizedStrings.Get("UnknowBookLocation");
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.ContainsKey("BookID"))
            {
                client.GetBookByIDCompleted += Client_GetBookByIDCompleted;
                client.GetBookByIDAsync(Convert.ToInt32(NavigationContext.QueryString["BookID"]));
            }
            
            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("ShowOnMapButton");
            (ApplicationBar.Buttons[1] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("FindBookButton");
            (ApplicationBar.Buttons[2] as ApplicationBarIconButton).Text = Localization.LocalizedStrings.Get("ReturnBookButton");
            ApplicationBar.BackgroundColor = CurrentSettings.Instance.ForegroundColor.Color;
        }

        private void ImageOnline_ImageFailed(object sender, ExceptionRoutedEventArgs e)
        {
            try
            {
                BitmapImage imageLocal = new BitmapImage();
                string path = this.book.CoverImagePath.Substring(1, this.book.CoverImagePath.Length - 1);
                StreamResourceInfo sr = Application.GetResourceStream(new Uri(path, UriKind.Relative));
                imageLocal.SetSource(sr.Stream);
                this.coverImage.Source = imageLocal;
            }
            catch (Exception)
            {
                StreamResourceInfo sr = Application.GetResourceStream(new Uri("Images/NoImage.jpg", UriKind.Relative));
                BitmapImage imageNoImage = new BitmapImage();
                imageNoImage.SetSource(sr.Stream);
                this.coverImage.Source = imageNoImage;
                return;
            }
        }

        #region User Input
        private void CoverImage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/ImagePage.xaml?ImagePath=" + this.book.CoverImagePath, UriKind.Relative));
        }

        private void ShowOnMapButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(String.Format("/Pages/MapPage.xaml?Latitude={0}&Longitude={1}", book.Address.Lat, book.Address.Lon), UriKind.Relative));
        }

        private void FindBookButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BookFindPage.xaml?BookID=" + book.ID.ToString(), UriKind.Relative));
        }

        private void ReturnBookButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/BookReturnPage.xaml?BookID=" + book.ID.ToString(), UriKind.Relative));
        }
        #endregion
    }
}